<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogAddgsVisible"
                   @close="closeDialogAddgsVisible">

            <el-form ref="addForm" :model="addForm">
                <el-form-item label="商品分类">
                    <el-cascader
                            v-model="value"
                            :options="options"
                            :props="{ expandTrigger: 'hover' }"
                            @change="handleChange"></el-cascader>
                </el-form-item>
                <el-form-item label="商品名称">
                    <el-input v-model="addForm.name" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="商品简介">
                    <el-input v-model="addForm.detail" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="商品库存">
                    <el-input v-model="addForm.stock" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="商品售价">
                    <el-input v-model="addForm.price" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="商品图片">
                    <div v-if="dialogImageUrl!==''" class="block">
                        <el-image :src="dialogImageUrl"></el-image>
                    </div>
                    <el-upload
                            action="http://localhost:8083/admin/product/file"
                            list-type="picture-card"
                            :multiple="false"
                            name='file'
                            :with-credentials='true'
                            :on-success='handleAvatarSuccess'
                            :before-upload='beforeAvatarUpload'
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddgsVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAddForm()">确 定</el-button>
            </div>
        </el-dialog>
        <el-row>
            <el-button type="primary" @click="addgsForm"><i class="el-icon-plus"></i>新增商品</el-button>
            <el-button type="danger"><i class="el-icon-download"></i>下架商品</el-button>
            <el-button type="success"><i class="el-icon-upload2"></i>上架商品</el-button>
        </el-row>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column fixed prop="id" label="商品编号" width="150"></el-table-column>
            <el-table-column fixed prop="name" label="商品名" width="120"></el-table-column>
            <el-table-column fixed prop="detail" label="商品简介" width="300"></el-table-column>
            <el-table-column fixed prop="image" label="商品图片" width="120">
                <template slot-scope="scope">
                    <el-popover placement="right" trigger="hover">
                        <img :src="scope.row.image"
                             style="height: 200px;width: 200px"/>
                        <img slot="reference" :src="scope.row.image"
                             :alt="scope.row.image" style="height: 38px;width: 38px;cursor: pointer">
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column fixed prop="stock" label="商品库存" width="120">
            </el-table-column>
            <el-table-column fixed prop="price" label="商品价格" width="120">
            </el-table-column>
            <el-table-column fixed prop="status" label="上下架状态" width="120">
                <template slot-scope="scope">
                    {{scope.row.status===1?'已上架':'已下架'}}
                </template>
            </el-table-column>
            <el-table-column fixed prop="createTime" label="创建时间" width="120">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="updateForm(scope.row.id)">编辑</el-button>
                    <el-button @click="deleteProductById(scope.row.id)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="m-pagination">
            <el-pagination
                    :hide-on-single-page="value"
                    :total="pageTotal"
                    layout="prev, pager, next"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            ></el-pagination>
        </div>


    </div>
</template>

<script>
    import {
        addProduct,
        deleteProduct,
        getAdminProductList,
        getCategoryListForVue,
        getProductDetail
    } from "../../../utils/apis";

    export default {
        name: "Product",
        methods: {
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum = val
                this.adminProductList()
            },
            adminProductList() {
                getAdminProductList({
                    "pageNum": this.pageNum,
                    "pageSize": this.pageSize
                }).then(res => {
                    this.tableData = res.data.list
                    this.pageTotal = res.data.total
                })
            }
            , addgsForm() {
                this.dialogAddgsVisible = true;
                //初始化
                this.addForm = {
                    id: "",
                    name: "",
                    image: "",
                    detail: "",
                    categoryId: "",
                    price: "",
                    stock: "",
                    status: ""
                }
                this.title = "新增商品"

            },
            deleteProductById(id) {
                console.log(id)
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteProduct({id: id}).then(res => {
                        console.log(res)
                        if (res.status === 10000) {
                            this.dialogAddgsVisible = false;
                            this.$message({
                                title: "success",
                                message: "success",
                                type: "success"
                            });
                            this.adminProductList()
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            updateForm(id) {
                console.log(id)
                getProductDetail({id: id}).then(res => {
                    this.addForm.id = res.data.id
                    this.addForm.status = res.data.status
                    this.addForm.image = res.data.image
                    this.addForm.categoryId = res.data.categoryId
                    this.addForm.price = res.data.price
                    this.addForm.stock = res.data.stock
                    this.addForm.name = res.data.name
                    this.addForm.detail = res.data.detail
                    this.dialogImageUrl = res.data.image
                })
                this.dialogAddgsVisible = true;
                this.title = "更新商品"

            },
            saveAddForm() {
                this.addForm.status = 1
                addProduct({...this.addForm}).then(res => {
                    console.log(res)
                    if (res.status === 10000) {
                        this.dialogAddgsVisible = false;
                        this.$message({
                            title: "success",
                            message: "success",
                            type: "success"
                        });
                        this.adminProductList()
                    }

                })
            },
            /**
             *关闭或取消模态框，清空值
             * @param
             */
            closeDialogAddgsVisible() {

                this.$refs.addForm.resetFields();//element封装的方法,清空模态框的值
                this.title = "" //初始化title的值
                this.addForm = {
                    name: "",
                    image: "",
                    detail: "",
                    categoryId: "",
                    price: "",
                    stock: "",
                    status: ""
                }
                this.dialogVisible = false
                this.dialogImageUrl = ""
            },
            handleChange(value) {
                console.log(value.length);
                this.addForm.categoryId = value[value.length - 1]
            },
            getCategory() {
                getCategoryListForVue().then(res => {
                    console.log(res)
                    this.options = res.data
                })
            },
            handleAvatarSuccess(res) {
                if (res.status === 10000) { //这里根据接口返回的去判断
                    this.addForm.image = res.data  //拿到图片的路径
                }
            },

//限制上传时的文件格式大小
            beforeAvatarUpload(file) {
                const isJPG = file.type === "image/jpeg" || file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 3;
                if (!isJPG) {
                    this.$message.error("上传图片只能是 JPG 和 Png 格式!");
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error("上传图片大小不能超过 3MB!");
                    return false;
                }
            },

        },
        mounted() {
            this.adminProductList()
            this.getCategory()
        },
        data() {
            return {
                pageNum: 1,
                pageSize: 10,
                pageTotal: 0,
                value: false,
                tableData: [],
                dialogAddgsVisible: false,
                options: [],
                dialogVisible: false,
                disabled: false,
                dialogImageUrl: "",
                title:'',
                addForm: {
                    name: "",
                    image: "",
                    detail: "",
                    categoryId: "",
                    price: "",
                    stock: "",
                    status: ""
                }
            }
        }
    }
</script>

<style scoped>
    .m-pagination {
        width: 100%;
        text-align: right;
    }
</style>
